package jee.demo.pro.app;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public final class AppConfig {
    private static final Logger LOGGER = LoggerFactory.getLogger(AppConfig.class);

    private static final Properties appProperties = new Properties();

    public static boolean SHUTDOWN = false;
    private static boolean initialized = false;

    public static boolean DEV;
    public static String CO_NAME;
    public static String DOMAIN;
    public static String HOST;
    public static String SITE_URL;
    public static String META_KEYWORD;
    public static String META_DESCRIPTION;
    public static String PUB_DATE;

    public static int CAPTCHA_LENGTH;
    public static String CAPTCHA_STRING;

    private static void load0(String filename) {
        // 处理用 maven 跑 unit tests 时候的路径问题
        String classpath = AppConfig.class.getResource("/").getPath().replace("test-", "");
        InputStream is = null;
        try {
            is = new FileInputStream(classpath + filename);
            appProperties.load(is);
        } catch (IOException e) {
            LOGGER.info("Resource[{}] not found!", filename);
        }
        try {
            if (is != null) is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void load() {
        appProperties.clear();
        // 处理用 maven 跑 unit tests 时候的路径问题
        load0("/app.properties");
        // 使用/dev.properties文件的配置覆盖/app.properties的配置，打war包时过滤掉/dev.properties
        load0("/dev.properties");

        DEV = AppConfig.class.getResource("/dev.properties") != null;
        CO_NAME = (String) appProperties.get("CO_NAME");
        DOMAIN = (String) appProperties.get("DOMAIN");
        HOST = (String) appProperties.get("HOST");
        SITE_URL = (String) appProperties.get("SITE_URL");
        PUB_DATE = (String) appProperties.get("PUB_DATE");

        META_DESCRIPTION = (String) appProperties.get("META_DESCRIPTION");
        META_KEYWORD = (String) appProperties.get("META_KEYWORD");

        CAPTCHA_LENGTH = Integer.valueOf(String.valueOf(appProperties.get("CAPTCHA_LENGTH")));
        CAPTCHA_STRING = String.valueOf(appProperties.get("CAPTCHA_STRING"));
    }

    /**
     * 在ServletContext初始化时启动.
     */
    public static void init() {
        if (initialized) return;
        load();
        initialized = true;
    }

    public static void destroy() {
        SHUTDOWN = true;
    }
}
